package com.kclmedu.springsecuritydb.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
* @ProjectName:
* @Package:        com.kclmedu.springsecuritynodb.controller
* @ClassName:      IndexController
* @Description:    控制器
* @Author:         Teacher.YE
* @CreateDate:     2019/7/11 22:11
* @Version:        1.0.0
*/
@Slf4j
@RestController
public class IndexController {

    @RequestMapping(value = "index")
    public String index() {
        log.debug("--- 进入IndexController的 index方法中...");
        String currentUser = "";
        //可以通过如下方法来获取登录的用户名, 也可以通过 @AuthenticationPrincipal 注解来注入一个 Principal对象
        //通过安全上下文的持久者来获取安全上下文，并获取认证对象后再获取“当事人”
        System.out.println(">>> Authentication对象的类型： "+SecurityContextHolder.getContext().getAuthentication().getClass());
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //判断这个 principal 是否是 UserDetail对象
        if(principal instanceof UserDetails) {
            currentUser = ((UserDetails) principal).getUsername();
        } else {
            currentUser = principal.toString();
        }
        //
        return "Hello,Spring Security!!!, current user is: "+currentUser;
    }

    @RequestMapping(value = "hello")
    public String hello() {
        //
        log.info("-- 进入IndexController的hello方法之中...");
        //
        return "同样会被拦截...";
    }
}
